﻿using Orleans;
using Pay.Service.user;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pay.Model.Dto;
using Pay.Container;
using Pay.Dal;
using Pay.Core.exception;
using Pay.Common.Encrypt;
using Pay.Model.Model;
using Newtonsoft.Json;
using System.Configuration;
using Dapper;
using Pay.DalImplement;
using Pay.Cache;
using Pay.Model.Interfaces;
using Pay.Model.Enums;

namespace Pay.ServiceImplement.user
{
    public class UserServiceImplement : Grain, IUserSerive
    {
        public async Task<MerchantInfo> GetMerchantById(long id)
        {
            var instance = LocManager.Resolve<IUserDal>();

            return await instance.GetMerchantById(id);
        }
        /// <summary>
        /// 新增商家用户
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<long> AddMerchantUser(MerchantInfo info)
        {
            var instance = LocManager.Resolve<IUserDal>();

            return await instance.AddMerchantUser(info);


        }
        public async Task<bool> Add(UserAddModel user)
        {
            var instance = LocManager.Resolve<IUserDal>();
            var roleService = LocManager.Resolve<IRoleDal>();
            var model = new UserInfo()
            {
                CreateTime = DateTime.Now,
                Type = user.type,
                Email = "",
                IsEnable = true,
                Pwd = user.Pwd,
                UserName = user.UserName,
                MerchantId = user.MerchantId
            };
            var id = await instance.Add(model);
            var userRole = new UserRoleInfo()
            {
                RoleId = user.Role,
                UserId = id,
            };
            return await roleService.Add(userRole) > 0 ? true : false;
        }

        public async Task<bool> Delete(long userId)
        {
            var instance = LocManager.Resolve<IUserDal>();
            var model = await instance.GetUserById(userId);
            if (model == null) throw new LotException("删除的用户不存在");
            return await instance.Delete(model);
        }

        public async Task<List<Menu>> GetAllMeun(long userId)
        {
            var instance = LocManager.Resolve<IUserDal>();
            var data = await instance.GetAllPermisson(userId);
            List<Menu> list = new List<Menu>();
            if (data.Any())
            {

                foreach (var item in data)
                {
                    var temp = list.Where(c => c.Name == item.MenuName).FirstOrDefault();
                    if (temp != null)
                    {
                        temp.Data.Add(new ActionController() { ActionName = item.ActionName, ControllerName = item.ControllerName, PermissionNamge = item.PermissionName });
                    }
                    else
                    {
                        list.Add(new Menu()
                        {
                            Data = new List<ActionController>() { new ActionController() { ActionName = item.ActionName, ControllerName = item.ControllerName, PermissionNamge = item.PermissionName } },
                            Name = item.MenuName
                        });
                    }
                }
            }

            return list;
        }

        public async Task<IPagedOutput<UserOutPut>> GetUserPage(long? mId, UserType? type, string searchWord, DateTime? timeBegin = null, DateTime? timeEnd = null, int offset = 10, int rows = 1)
        {
            var instance = LocManager.Resolve<IUserDal>();
            return await instance.GetUserPage(mId, type, searchWord, timeBegin, timeEnd, offset, rows);
        }

        public async Task<bool> Update(UserInfo user)
        {
            var instance = LocManager.Resolve<IUserDal>();
            //var model = new UserInfo()
            //{
            //    Id = user.Id,
            //    CreateTime = DateTime.Now,
            //    Email = user.Email,
            //    ExpireTime = user.ExpireTime,
            //    ImageUrl = user.ImageUrl,
            //    IsEnable = true,
            //    NikeName = user.NikeName,
            //    Phone = user.Phone,
            //    Pwd = user.Pwd,
            //    Tid = user.Tid,
            //    UserName = user.UserName
            //};
            return await instance.Update(user);
        }

        public async Task<LoginOutPut> UserLogin(LoginOutPut input)
        {
            if (string.IsNullOrWhiteSpace(input.UserName) || string.IsNullOrWhiteSpace(input.Pwd))
                throw new LotException("用户名或密码为空");
            var instance = LocManager.Resolve<IUserDal>();

            var user = await instance.GetUserByName(input.UserName);
            if (user == null) throw new LotException("用户不存在");
            if (!input.Pwd.Equals(user.Pwd)) throw new LotException("密码错误");

            //AuthInfo auth = new AuthInfo() {
            //     LoginTime=DateTime.Now,
            //      Pwd=user.Pwd,
            //      UserName=user.UserName
            //};

            //var baseInfo= JsonConvert.SerializeObject(auth);
            //var token=  DesEncrypt.EncryptDES(baseInfo, ConfigurationManager.AppSettings["encrypt:key"]);
            var token = Guid.NewGuid().ToString();
            //放入redis
            LocManager.Resolve<ICacheManager>().Set(token, user, TimeSpan.FromHours(2));
            //查询权限
            var permisson = await GetAllMeun(user.Id);
            var outPut = new LoginOutPut()
            {

                UserName = user.UserName,
                Menu = permisson,
                Token = token,
                UserId = user.Id
            };

            return outPut;
        }

        public async Task<UserInfo> GetByUserName(string userName)
        {
            var instance = LocManager.Resolve<IUserDal>();

            return await instance.GetUserByName(userName);

        }

        public async Task<UserInfo> GetUserById(long userId)
        {
            var instance = LocManager.Resolve<IUserDal>();
            return await instance.GetUserById(userId);
        }
        /// <summary>
        /// 更新商户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<bool> UpdateMerchant(MerchantInfo user)
        {
            var instance = LocManager.Resolve<IUserDal>();
            return await instance.UpdateMerchant(user);
        }
    }
}